let xxplugins = {};
import localStorage from "@/utils/localStorage";

xxplugins.install = function (Vue, vm) {
  const IsStringNull = function (res) {
    if (res == null || res == undefined) return true;
    if (
      res.toString() == "" ||
      res.toString() == " " ||
      res.toString() == "null" ||
      res.toString() == "NULL"
    )
      return true;
    if (res.toString().length == 0) return true;
    return false;
  };

  const isNull = function (res) {
    if (res == null || res == undefined) return true;

    let _toString = res.toString();

    if (["", " ", "null", "NULL"].indexOf(_toString) > -1) return true;

    if (_toString == "[object Object]" && Object.keys(res).length == 0)
      return true;
    return false;
  };

  /*============================================================================
		 Promise 方式封装request V2
		 code by xiaox 2022-03-02
	============================================================================*/
  const request = async function (
    link,
    data = "",
    method = "Get",
    header = {}
  ) {
    const _root = vm.GLOBAL.Domain;
    const _rediret = vm.$store.getters.apphost;
    // const _token = vm.$store.getters.token
    // console.log('token:', _token)
    // console.log(_root)
    uni.showLoading();
    if (header == "" && !IsStringNull(_token)) {
      header.Authorization = "Bearer " + _token;
    }

    if (!IsStringNull(_rediret)) header.redirectHost = _rediret;
    let _url = link.startsWith("http") ? link : `${_root}/api/${link}`;
    _url = _url.replace(/[^:]\/\//g, (w) => {
      return w.substring(0, 2);
    });

    console.log(`[${method} Request] URL:${_url}`);
    console.log(`[${method} Request] DATA:${JSON.stringify(data)}`);
    console.log(`[${method} Request] HOST:${header.redirectHost}`);

    let [error, res] = await uni.request({
      url: _url,
      data: data,
      header: header,
      method: method,
    });

    uni.hideLoading();
    if (error) {
      return new Promise((resolve, reject) => {
        reject(error);
      });
    }
    console.log(`[Request Result] ${JSON.stringify(res)}`);
    return res;
  };

  const alert = function (msg) {
    const _oftype = Object.prototype.toString.call(msg);
    uni.showToast({
      title:
        _oftype == "[object Object]" ? JSON.stringify(msg) : msg.toString(),
      duration: 2000,
      icon: "none",
    });
  };

  const confirm = function (msg, title = "") {
    return new Promise((resolve, reject) => {
      uni.showModal({
        title: title,
        content: msg,
        success: function (res) {
          if (res.confirm) {
            resolve();
          } else if (res.cancel) {
            reject();
          }
        },
      });
    });
  };

  const confirmOnly = function (msg, title = "") {
    return new Promise((resolve, reject) => {
      uni.showModal({
        title: title,
        content: msg,
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            resolve();
          } else if (res.cancel) {
            reject();
          }
        },
      });
    });
  };

  const isWithoutHost = function () {
    if (vm.$store.getters.apphost == "") {
      return true;
    } else {
      return false;
    }
  };

  const back = function (_url, _params = {}) {
    uni.navigateBack();
  };

  const scan = function (onlyCam = false) {
    return new Promise((resolve, reject) => {
      uni.scanCode({
        onlyFromCamera: onlyCam,
        success: function (res) {
          if (res.result) {
            resolve(res.result);
          } else {
            reject("无效二维码");
          }
        },
        fail: function (err) {
          reject("扫码失败！");
        },
      });
    });
  };

  const getPost = function (tag, id) {
    return new Promise((resolve, reject) => {
      uni
        .createSelectorQuery()
        .in(tag)
        .select(`#${id}`)
        .boundingClientRect((data) => {
          resolve(data);
        })
        .exec();
    });
  };

  const typeOf = function (target) {
    return /^\[object (\w+)]$/
      .exec(Object.prototype.toString.call(target))[1]
      .toLocaleLowerCase();
  };

  const objToParam = function (obj) {
    var res = "";
    for (let key in obj) {
      console.log(key);

      res += `${res != "" ? "&" : ""}${key}=${obj[key]}`;
      console.log(res);
    }
    return `?${res}`;
  };

  Vue.prototype.$typeOf = typeOf;
  Vue.prototype.$confirm = confirm;
  Vue.prototype.$alert = alert;
  Vue.prototype.$ls = localStorage;
  Vue.prototype.$back = back;
  Vue.prototype.$request = request;
  Vue.prototype.$isNull = isNull;
  Vue.prototype.$isWithoutHost = isWithoutHost;
  Vue.prototype.$scan = scan;
  Vue.prototype.$getPost = getPost;
  Vue.prototype.$objToParam = objToParam;
  Vue.prototype.$confirmOnly = confirmOnly;
};
export default xxplugins;
